package UI;

import Model.student;
import Service.Crudservice;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/student")
public class studentControl extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();

        //判断上次的cookie是否存在
        Cookie[] cookies = req.getCookies();
        Boolean cookie = false;
        if (cookies != null) {
            for (Cookie cookie1 : cookies) {
                if (cookie1.getName().equals("YN")) {
                    cookie = true;
                    break;
                }
            }
        }
        if (cookie) {//如果cookie为真，这里什么都不做，直接走下面的页面
        } else if (!("666".equals(session.getAttribute("YN")))) {
            //resp.sendRedirect("error.jsp");
            req.getRequestDispatcher("error.jsp").forward(req,resp);
            return;
        } else {
            String yn = (String) session.getAttribute("YN");
            //只要正常登录用户信息持久化
            Cookie yn1 = new Cookie("YN1", yn);
            yn1.setMaxAge(60 * 60 * 24);
            resp.addCookie(yn1);
        }
        try {
            req.setCharacterEncoding("utf-8");
            Crudservice crudservice = new Crudservice();
            ArrayList<student> student1 = crudservice.student();
            req.setAttribute("list", student1);
            req.getRequestDispatcher("Pageselect.jsp").forward(req, resp);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
